package com.motu.vertx.module.utility.mysql;





import java.util.List;

import io.vertx.core.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.motu.vertx.module.utility.toolset.ErrorWord;

//import com.motu.emperor.module.common.utility.ErrorWord;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.sql.SQLOptions;

public class MysqlUtils {
	private static final Logger logger = LoggerFactory.getLogger(MysqlUtils.class);

	/***
	 * 获取数据库连接池配置
	 * @param fileName 配置文件名
	 * @param poolSize 指定连接池大小
	 * @return 配置
	 */
	public static JsonObject getDBConfig(String fileName,int poolSize){
		if(poolSize == 0){//不指定连接池大小，按默认值

			if(fileName.equalsIgnoreCase("hikari_game")){
				poolSize = 30;
			}else if(fileName.equalsIgnoreCase("hikari_common")){
				poolSize = 3;
			}else if(fileName.equalsIgnoreCase("hikari_server")){
				poolSize = 10;
			}else if(fileName.equalsIgnoreCase("hikari_log")){
				poolSize = 20;
			}else if(fileName.equalsIgnoreCase("hikari_web")){
				poolSize = 3;
			}else{
				poolSize = 10;
			}
		}
		JsonObject dbconfig = new JsonObject().put("provider_class", "io.vertx.ext.jdbc.spi.impl.HikariDataSourceProvider")
				.put("property_file", fileName+".properties").put("pool_size", poolSize);
		return dbconfig;
	}

	/***
	 * 查询数据库，返回第一条记录
	 * @param jdbcClient
	 * @param sql
	 * @param params
	 * @param handler
	 */
	public static void queryJsonObjectFromDb(JDBCClient jdbcClient, String sql, JsonArray params, Handler<AsyncResult<JsonObject>> handler) {
		//		System.out.println("queryJsonObjectFromDb test git");
		//		git pull
		jdbcClient.queryWithParams(sql, params, res->{
			if(res.succeeded()){
				List<JsonObject> rows = res.result().getRows();
				if (rows.isEmpty()){
					handler.handle(Future.succeededFuture(null));
				} else{
					JsonArray array = new JsonArray(rows);
					handler.handle(Future.succeededFuture(array.getJsonObject(0)));
				}
			}else{
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
				res.cause().printStackTrace();
				handler.handle(Future.failedFuture(res.cause().getMessage()));
			}
		});
	}
	/***
	 * 查询数据库，返回异步结果
	 * @param jdbcClient
	 * @param sql
	 * @param params
	 * @param handler
	 */
	public static void queryJsonArrayFromDb(JDBCClient jdbcClient, String sql, JsonArray params, Handler<AsyncResult<JsonArray>> handler) {
		if(jdbcClient == null) {
			handler.handle(Future.failedFuture("jdbcClient is null"));
		}else {
			jdbcClient.queryWithParams(sql, params, res->{
				if(res.succeeded()){
					List<JsonObject> rows = res.result().getRows();
					if (rows.isEmpty()){
						handler.handle(Future.succeededFuture(new JsonArray()));
					} else{
						JsonArray array = new JsonArray(rows);
						handler.handle(Future.succeededFuture(array));
					}
				}else{
					logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
					res.cause().printStackTrace();
					handler.handle(Future.failedFuture(res.cause().getMessage()));
				}
			});
		}
	}
	/***
	 * 查询数据库，并返回一个future
	 * @param jdbcClient
	 * @param sql
	 * @param params
	 * @return
	 */
	public static Future<JsonArray> queryJsonArrayFromDb(JDBCClient jdbcClient, String sql, JsonArray params) {
		Promise<JsonArray> fut = Promise.promise();
		jdbcClient.queryWithParams(sql, params, res->{
			if(res.succeeded()){
				List<JsonObject> rows = res.result().getRows();
				if (rows.isEmpty()){
					fut.complete(new JsonArray());
				} else{
					JsonArray array = new JsonArray(rows);
					fut.complete(array);
				}
			}else{
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
				res.cause().printStackTrace();
				fut.fail(res.cause().getMessage());
			}
		});
		return fut.future();
	}
	
	/***
	 * 先检查是否存在表，再查询数据库，并返回一个future
	 * @param jdbcClient
	 * @param sql
	 * @param params
	 * @return
	 */
	public static Future<JsonArray> check_queryJsonArrayFromDb(JDBCClient jdbcClient, String tableName, String sql, JsonArray params) {
		Promise<JsonArray> fut = Promise.promise();
		String check_sql = "SELECT table_name FROM information_schema.TABLES WHERE table_name = '" + tableName + "';";
		jdbcClient.queryWithParams(check_sql, new JsonArray(), checkRes->{
			if(checkRes.succeeded()){
				List<JsonObject> checkRows = checkRes.result().getRows();
				if (checkRows.isEmpty()){
					logger.error("----############---- sql: Table "+tableName+" doesn't exist");
					fut.complete(new JsonArray());
				} else{
					jdbcClient.queryWithParams(sql, params, res->{
						if(res.succeeded()){
							List<JsonObject> rows = res.result().getRows();
							if (rows.isEmpty()){
								fut.complete(new JsonArray());
							} else{
								JsonArray array = new JsonArray(rows);
								fut.complete(array);
							}
						}else{
							logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
							res.cause().printStackTrace();
							fut.fail(res.cause().getMessage());
						}
					});
				}
			}else{
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+checkRes.cause().getMessage());
				checkRes.cause().printStackTrace();
				fut.fail(checkRes.cause().getMessage());
			}
		});
		return fut.future();
	}

	/***
	 * 更新到数据库
	 * @param jdbcClient
	 * @param sql
	 * @param params
	 * @param handler
	 */
	public static void updateToDb(JDBCClient jdbcClient,String sql,JsonArray params, Handler<AsyncResult<Object>> handler) {
		jdbcClient.updateWithParams(sql, params, res->{
			if(res.succeeded()){
				handler.handle(Future.succeededFuture(res.result().getUpdated()));
			}else{
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
				res.cause().printStackTrace();
				handler.handle(Future.failedFuture(res.cause().getMessage()));
			}
		});

	}
	/***
	 * 插入数据库并取回自增id
	 * @param jdbcClient
	 * @param sql
	 * @param params
	 * @return
	 */
	public static void insertAndGetID(JDBCClient jdbcClient,String sql,JsonArray params, Handler<AsyncResult<Long>> handler) {
		jdbcClient.updateWithParams(sql, params, ar -> {
			if (ar.failed()) {
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+ar.cause().getMessage());
				ar.cause().printStackTrace();
				handler.handle(Future.failedFuture(ar.cause().getMessage()));
			} else {
				JsonArray array = ar.result().getKeys();
				if (!array.isEmpty()){
					Long id = (Long) array.getValue(0);
					handler.handle(Future.succeededFuture(id));
				} else{
					handler.handle(Future.succeededFuture(0l));
				}
			}
		});
	}
	//	/***
	//	 * 获取单条数据，如"select id,username from userinfo where id = 1",返回的是不带字段名的array[1,"ibm"],如果搜索不到则返回null
	//	 * @param jdbcClient
	//	 * @param sql
	//	 * @param params
	//	 * @param handler
	//	 */
	//	public static void querySingleFromDb(JDBCClient jdbcClient, String sql, JsonArray params, Handler<AsyncResult<JsonArray>> handler) {
	//		jdbcClient.querySingleWithParams(sql, params, res->{
	//			if(res.succeeded()){
	//				JsonArray array = res.result();
	//				handler.handle(Future.succeededFuture(array));
	//			}else{
	//				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
	//				res.cause().printStackTrace();
	//				handler.handle(Future.failedFuture(res.cause().getMessage()));
	//			}
	//		});
	//	}

}
